<?php

namespace plugin\admin\app\controller;

use support\Request;
use support\Response;
use plugin\admin\app\model\AfterSale;
use plugin\admin\app\controller\Crud;
use support\exception\BusinessException;

/**
 * 售后维修 
 */
class AfterSaleController extends Crud
{

    /**
     * @var AfterSale
     */
    protected $model = null;

    /**
     * 构造函数
     * @return void
     */
    public function __construct()
    {
        $this->model = new AfterSale;
    }

    public function select(Request $request): Response
    {
        [$where, $format, $limit, $field, $order] = $this->selectInput($request);
        $query = $this->doSelect($where, $field, $order);
        $query = $query->with([
            'attachments' => function ($q) {
                $q->select('path', 'after_sale_id');
            },
            'user' => function($q){
                $q->select('id', 'phone');
            },
            'device' => function($q){
                $q->select('sn','gateway_id');
            },
        ]);

        if($userPhone = $request->get('user_phone')){
            $query->leftJoin('wa_users as u', 'u.id','user_id')->where('u.phone', $userPhone);

        }

        if($gatewayId = $request->get('gateway_id')){
            $query->leftJoin('wa_devices as d', 'd.sn','wa_after_sales.sn')->where('d.gateway_id', $gatewayId);
        }

        return $this->doFormat($query, $format, $limit);
    }

    /**
     * 浏览
     * @return Response
     */
    public function index(): Response
    {
        return view('after-sale/index');
    }

    /**
     * 插入
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function insert(Request $request): Response
    {
        if ($request->method() === 'POST') {
            return parent::insert($request);
        }
        return view('after-sale/insert');
    }

    /**
     * 更新
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function update(Request $request): Response
    {
        if ($request->method() === 'POST') {
            return parent::update($request);
        }
        return view('after-sale/update');
    }
}
